package com.jdew.thkj.activity;

import android.app.Activity;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.jdew.thkj.R;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;

import java.util.HashMap;

import butterknife.Bind;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class SetingTwoLevelActivity extends BaseActivity {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.tel)
    TextView tel;
    @Bind(R.id.yzcode)
    EditText yzcode;
    @Bind(R.id.tvcode)
    TextView tvcode;
    @Bind(R.id.mima)
    EditText mima;
    @Bind(R.id.cansee)
    ImageView cansee;
    @Bind(R.id.mima_sure)
    EditText mimaSure;
    @Bind(R.id.cansee_sure)
    ImageView canseeSure;
    @Bind(R.id.setting)
    Button setting;
    @Bind(R.id.view)
    LinearLayout view;
    private int type = 0;
    private int type2 = 0;
    private String sessionId;
    private String telcode;
    private int typeId=1;

    @Override
    public int bindLayout() {
        return R.layout.activity_two_level;
    }

    @Override
    public void initView(View view) {
        back.setVisibility(View.VISIBLE);
        title.setText("二级密码");
        back.setOnClickListener(this);
        cansee.setOnClickListener(this);
        canseeSure.setOnClickListener(this);
        tvcode.setOnClickListener(this);
        setting.setOnClickListener(this);
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        telcode=sp.getString("code","");
        tel.setText(sp.getString("userPhone", ""));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.tvcode: {
                if (RegexValidateUtils.checkCellphone(tel.getText().toString())) {
                    typeId = 1;
                } else {
                    typeId = 2;
                }
                getCode();
            }
            break;
            case R.id.cansee: {
                if (type == 0) {
                    cansee.setImageResource(R.mipmap.r_in);
                    mima.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    type = 1;
                } else {
                    cansee.setImageResource(R.mipmap.r_un);
                    mima.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    type = 0;
                }
                mima.setSelection(mima.getText().toString().length());
            }
            break;
            case R.id.cansee_sure: {
                if (type2 == 0) {
                    canseeSure.setImageResource(R.mipmap.r_in);
                    mimaSure.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    type2 = 1;
                } else {
                    canseeSure.setImageResource(R.mipmap.r_un);
                    mimaSure.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    type2 = 0;
                }
                mimaSure.setSelection(mimaSure.getText().toString().length());
            }
            break;
            case R.id.setting: {
                SetTwoLevelCipher();
            }
            break;
            default:
                break;
        }
    }

    /**
     * 取消倒计时
     *
     * @param v
     */
    public void oncancel(View v) {
        timer.cancel();
    }

    /**
     * 开始倒计时
     *
     * @param v
     */
    public void restart(View v) {
        timer.start();
    }

    private CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            tvcode.setEnabled(false);
            tvcode.setTextColor(Color.GRAY);
            tvcode.setText((millisUntilFinished / 1000) + "秒后可重发");
        }

        @Override
        public void onFinish() {
            tvcode.setEnabled(true);
            tvcode.setTextColor(getResources().getColor(R.color.theme_color));
            tvcode.setText("发送验证码");
            timer.cancel();
        }
    };

    public void getCode() {
        String timesamp=RegexValidateUtils.getTime13();
        String numsamp=RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetCode(tel.getText().toString().trim(),typeId, RegexValidateUtils.getUniquePsuedoID(),timesamp,numsamp,MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp+numsamp+RegexValidateUtils.getUniquePsuedoID()+sp.getString("SignToken","")+"phone"+tel.getText().toString().trim()+"typeId"+typeId)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.getInstance(SetingTwoLevelActivity.this).showMessage("发送异常");
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    timer.start();
                    ToastUtils.getInstance(SetingTwoLevelActivity.this).showMessage(json.getString("message"));
                    telcode = json.getString("data");
                    editor.putString("yz_phone", tel.getText().toString().trim());
                    editor.putString("code", telcode);
                    editor.apply();
                } else {
                    ToastUtils.getInstance(SetingTwoLevelActivity.this).showMessage(json.getString("message"));
                }
            }
        });
    }

    public void SetTwoLevelCipher() {
        if (TextUtils.isEmpty(yzcode.getText())) {
            ToastUtils.getInstance(this).showMessage("请输入验证码");
            return;
        } else if (TextUtils.isEmpty(mima.getText())) {
            ToastUtils.getInstance(this).showMessage("请输入密码");
            return;
        } else if (TextUtils.isEmpty(mimaSure.getText())) {
            ToastUtils.getInstance(this).showMessage("请再次输入密码");
            return;
        } else if (mima.getText().toString().trim().length()!=6) {
            ToastUtils.getInstance(this).showMessage("请输入6位密码");
            return;
        }else if (mimaSure.getText().toString().trim().length()!=6) {
            ToastUtils.getInstance(this).showMessage("请输入密码");
            return;
        }else if (!mima.getText().toString().trim().equals(mimaSure.getText().toString().trim())) {
            ToastUtils.getInstance(this).showMessage("两次密码输入不一致");
            return;
        }
        String timesamp=RegexValidateUtils.getTime13();
        String numsamp=RegexValidateUtils.getRandom10();
        HashMap<String,Object> map=new HashMap();
        map.put("NewPwd",mimaSure.getText().toString().trim());
        map.put("Pwd",mima.getText().toString().trim());
        map.put("UserPhone",tel.getText().toString());
        String s=RegexValidateUtils.ASCIISort(timesamp+numsamp+RegexValidateUtils.getUniquePsuedoID()+sp.getString("SignToken","")+"NewPwd"+mima.getText().toString().trim()+"Pwd"+mimaSure.getText().toString().trim()+"UserPhone"+tel.getText().toString());
        String s2=MD5Utils.getMD5(s).toUpperCase();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).SetTwoLevelCipher(map,RegexValidateUtils.getUniquePsuedoID(),timesamp,numsamp,MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp+numsamp+RegexValidateUtils.getUniquePsuedoID()+sp.getString("SignToken","")+"NewPwd"+mima.getText().toString().trim()+"Pwd"+mimaSure.getText().toString().trim()+"UserPhone"+tel.getText().toString())).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.getInstance(SetingTwoLevelActivity.this).showMessage("发送异常");
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    timer.start();
                    ToastUtils.getInstance(SetingTwoLevelActivity.this).showMessage(json.getString("message"));
                    telcode = json.getString("data");
                    editor.putString("yz_phone", tel.getText().toString().trim());
                    editor.putString("code", telcode);
                    editor.apply();
                    finish();
                } else {
                    ToastUtils.getInstance(SetingTwoLevelActivity.this).showMessage(json.getString("message"));
                }
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }
}
